<?php
namespace app\api\controller;
use think\Db;
use app\factory\MqFactory;
use app\common\library\MysicLog;
/**
 *  分红队列
 * Class BackAbonusAccounts
 * @package app\task\queue
 */
class DivideReceives extends \think\Controller
{

    /* @var MysicLog $log */
    protected $log;

    /**
     * 构造方法
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function _initialize()
    {
        parent::_initialize();
        $this->log = MysicLog::instance();
    }

    /**
     * 出局处理
     * @return array|bool|mixed
     * @throws \think\exception\DbException
     */
    public function divideOut(){

        set_time_limit(0);

        try {

            $this->log->setFilename('divideReceives/divide');
            $this->log->info('开始', '期号变更分红队列出局处理');

            $rmq = MqFactory::instance();
            $processMessage = function ($envelope) {

                $msg = $envelope->getBody();
                $params= json_decode($msg,true);
                //出局处理
                $divideReceives = Db::name('divide_receives')
                    ->where(['wxapp_id'=>$params['wxapp_id'],'periods_num'=>$params['periods_num'],'type'=>0])
                    ->select();
                //查询配置
                $wxConfig = Db::name('wxapp_setting')
                    ->where(['wxapp_id'=>$params['wxapp_id']])
                    ->find();

                $this->log->info($wxConfig, '查询配置');


                $this->log->info(json_encode($divideReceives->toArray(),true), '获取期号变更分红队列出局数据');

                foreach ($divideReceives as $k=>&$v){

                    if($wxConfig['moneypercentstatus']==2){

                        Db::name('divide_receives')
                            ->where(['receives_id'=>$v['receives_id']])
                            ->update(['type'=>1]);
                        $user_balance_log = [];

                    }else{

                        if($v['balance']>0){
                            Db::name('user')->where(['user_id'=>$v['user_id']])->setInc('balance',$v['balance']);
                            $user_balance_log[] = [
                                'user_id'=>$v['user_id'],
                                'scene'=>50,
                                'money'=>$v['balance'],
                                'wxapp_id'=>$params['wxapp_id'],
                                'create_time'=>time(),
                            ];
                        }

                        Db::name('divide_receives')
                            ->where(['receives_id'=>$v['receives_id']])
                            ->update(['type'=>1,'small_change'=>$v['balance']]);
                        $extend = Db::name('divide_receives_user')
                            ->where(['receives_id'=>$v['receives_id']])
                            ->value('extend');
                        if($extend){
                            $extend_arr = json_decode($extend,true);
                            $extend_arr[] = [
                                'time'=>time(),
                                'type'=>3,
                                'money'=>'',
                                'times'=>$v['times']+1,
                                'status'=>1,
                                'order_no'=>'',
                                'refund_id'=>'',
                                'refund_fee'=>$v['balance'],
                            ];
                            $extend_arr = json_encode($extend_arr,256);
                            Db::name('divide_receives_user')
                                ->where(['receives_id'=>$v['receives_id']])
                                ->update(['extend'=>$extend_arr]);
                        }else{
                            $extend_arr = [[
                                'time'=>time(),
                                'type'=>3,
                                'money'=>'',
                                'times'=>$v['times']+1,
                                'status'=>1,
                                'order_no'=>'',
                                'refund_id'=>'',
                                'refund_fee'=>$v['balance'],
                            ]];
                            $extend_arr = json_encode($extend_arr,256);

                            Db::name('divide_receives_user')
                                ->insert(['receives_id'=>$v['receives_id'],'extend'=>$extend_arr,'create_time'=>time(),'update_time'=>time()]);
                        }

                    }


                }

                Db::name('user_balance_log')->insertAll($user_balance_log);

            };

            $rmq->run($processMessage, 'divideReceives','divideReceivesLog','divideReceivesLog');

            $this->log->info('结束', '期号变更分红队列出局处理');

        } catch (Throwable $e) {
            $this->log->info(exceptionLogFormat($e), '期号变更分红队列出局处理抛出异常');

        }


    }




    /**
     * 大额支付分账处理
     * @return array|bool|mixed
     * @throws \think\exception\DbException
     */
    public function largeDivide(){


        $this->log->setFilename('largeDivide/divide');
        $this->log->info('开始', '大额支付分账处理');

        try {
            $rmq = MqFactory::instance();
            $processMessage = function ($envelope) {

                $msg = $envelope->getBody();
                $this->log->info($msg, '接收数据');
                $params = json_decode($msg,true);

                //订单编号 order_no,bonus,recevies_id,order_id
                $divideReceives = Db::name('divide_receives')
                    ->where(['receives_id'=>$params['receives_id']])
                    ->find();
                $this->log->info($divideReceives, '分红数据');

                $orderInfo = Db::name('order')
                    ->where(['order_id'=>$params['order_id']])
                    ->field('pay_price,order_no')
                    ->find();
                $this->log->info($orderInfo, '订单数据');

                if($divideReceives){
                    //实际分账接收方记录表（用户）
                    $extend = Db::name('divide_receives_user')
                        ->where(['receives_id'=>$params['receives_id']])
                        ->value('extend');
                    $this->log->info($extend, '实际分账接收方记录表（用户）');

                    if($extend){
                        $extend_arr = json_decode($extend,true);
                        $extend_arr[] = [
                            'time'=>time(),
                            'type'=>3,
                            'money'=>$orderInfo['pay_price'],
                            'times'=>$divideReceives['times']+1,
                            'status'=>1,
                            'order_no'=>$orderInfo['order_no'],
                            'refund_id'=>'',
                            'refund_fee'=>$params['bonus'],
                        ];
                        $this->log->info($extend_arr, '实际分账接收方记录表数据1');

                        $extend_arr = json_encode($extend_arr,256);
                        Db::name('divide_receives_user')
                            ->where(['receives_id'=>$params['receives_id']])
                            ->update(['extend'=>$extend_arr]);
                    }else{
                        $extend_arr = [[
                            'time'=>time(),
                            'type'=>3,
                            'money'=>$orderInfo['pay_price'],
                            'times'=>$divideReceives['times']+1,
                            'status'=>1,
                            'order_no'=>$orderInfo['order_no'],
                            'refund_id'=>'',
                            'refund_fee'=>$params['bonus'],
                        ]];
                        $this->log->info($extend_arr, '实际分账接收方记录表数据2');
                        $extend_arr = json_encode($extend_arr,256);

                        Db::name('divide_receives_user')
                            ->insert(['receives_id'=>$params['receives_id'],'extend'=>$extend_arr,'create_time'=>time(),'update_time'=>time()]);
                    }

                    if($params['bonus']>0){

                        Db::name('dealer_user')->where(['user_id'=>$divideReceives['user_id']])->setInc('money',$params['bonus']);
                        $dealer_capital_log = [
                            'user_id'=>$divideReceives['user_id'],
                            'flow_type'=>30,
                            'money'=>$params['bonus'],
                            'wxapp_id'=>$divideReceives['wxapp_id'],
                            'create_time'=>time(),
                            'update_time'=>time(),
                        ];
                        $this->log->info($dealer_capital_log, '佣金记录');
                        Db::name('dealer_capital')->insert($dealer_capital_log);

                    }

//                    if($divideReceives['times']>45){
                        //更新divide_receives表
                        Db::name('divide_receives')
                            ->where(['receives_id'=>$params['receives_id']])
                            ->setInc('reward_money',$params['bonus']);
//                    }else{
//                        //更新divide_receives表
//                        Db::name('divide_receives')
//                            ->where(['receives_id'=>$params['receives_id']])
//                            ->setInc('refund_money',$params['bonus']);
//                    }


                    Db::name('divide_receives')
                        ->where(['receives_id'=>$params['receives_id']])
                        ->setInc('total_abonus',$params['bonus']);

                    Db::name('divide_receives')
                        ->where(['receives_id'=>$params['receives_id']])
                        ->setDec('balance',$params['bonus']);

                    Db::name('divide_receives')
                        ->where(['receives_id'=>$params['receives_id']])
                        ->setInc('times',1);
                }

            };

            $rmq->run($processMessage, 'largeDivide','largeDivideLog','largeDivideLog');

            $this->log->info('结束', '大额支付分账处理');

        } catch (Throwable $e) {
            $this->log->info(exceptionLogFormat($e), '大额支付分账处理抛出异常');

        }


    }

}